<template>
  <div class="chat-tool-bar">
    <div
      title="表情"
      class="icon iconfont icon-emoji"
      ref="emotionRef"
      @click.stop="showEmotionBox()"
    ></div>

    <div title="发送图片">
      <FileUpload
        :action="'/image/upload'"
        :maxSize="5 * 1024 * 1024"
        :fileTypes="[
          'image/jpeg',
          'image/png',
          'image/jpg',
          'image/webp',
          'image/gif',
        ]"
        @before="onImageBefore"
        @success="onImageSuccess"
        @fail="onImageFail"
      >
        <el-icon><Picture /></el-icon>
      </FileUpload>
    </div>
    <div title="发送文件">
      <FileUpload
        ref="fileUpload"
        :action="'/file/upload'"
        :maxSize="10 * 1024 * 1024"
        @before="onFileBefore"
        @success="onFileSuccess"
        @fail="onFileFail"
      >
        <el-icon><Wallet /></el-icon>
      </FileUpload>
    </div>
    <div
      title="回执消息"
      v-show="isGroup && memberSize <= 500"
      class="icon iconfont icon-receipt"
      :class="isReceipt ? 'chat-tool-active' : ''"
      @click="onSwitchReceipt"
    ></div>
    <div title="发送语音" class="el-icon-microphone" @click="showRecordBox()">
      <el-icon><Microphone /></el-icon>
    </div>
    <div
      title="语音通话"
      v-show="isPrivate"
      class="el-icon-phone-outline"
      @click="showPrivateVideo('voice')"
    >
      <el-icon><Iphone /></el-icon>
    </div>
    <div
      title="语音通话"
      v-show="isGroup"
      class="el-icon-phone-outline"
      @click="onGroupVideo()"
    >
      <el-icon><Iphone /></el-icon> {{ isPrivate }}
    </div>
    <div
      title="视频通话"
      v-show="isPrivate"
      class="el-icon-video-camera"
      @click="showPrivateVideo('video')"
    >
      <el-icon><VideoCamera /></el-icon>
    </div>
    <div
      title="聊天记录"
      class="el-icon-chat-dot-round"
      @click="showHistoryBox()"
    >
      <el-icon><ChatDotRound /></el-icon>
    </div>
  </div>
  <GroupMemberSelector
    ref="rtcSel"
    :group="group"
    @complete="onInviteOk"
  ></GroupMemberSelector>
  <Emotion ref="emoBoxRef" @emotion="onEmotion"></Emotion>
</template>

<script setup lang="ts">
import {
  Microphone,
  Iphone,
  VideoCamera,
  ChatDotRound,
  Picture,
  Wallet,
} from "@element-plus/icons-vue";
import { MESSAGE_STATUS } from "@/types/enums";
import element from "@/utils/element";
import { useChatStore } from "@/store/modules/chatStore";
const chatStore = useChatStore();
const props = defineProps({
  chat: Object as any,
  groupMembers: { type: Array } as any,
  isReceipt: Boolean,
  isBanned: Boolean,
  friend: Object as any,
  mine: Object as any,
  group: Object as any,
});
const emotionRef = ref(null) as any;
const rtcSelRef = ref(null) as any;
const emits = defineEmits([
  "setEmoBox",
  "showBannedTip",
  "moveChatToTop",
  "scrollToBottom",
  "sendMessageRequest",
]);
const emoBoxRef = ref(null);
const isPrivate = computed(() => {
  return props.chat && props.chat.type == "PRIVATE";
});

const isGroup = computed(() => {
  return props.chat && props.chat.type == "GROUP";
});
const memberSize = computed(() => {
  return props.groupMembers.filter((m: any) => !m.quit).length;
});
function onEmotion(emoText: string) {
  // chatInputEditorRef.value?.insertEmoji(emoText);
}
function showEmotionBox() {
  if (emotionRef.value) {
    let width = emotionRef.value?.offsetWidth;
    let left = element.fixLeft(emotionRef.value);
    let top = element.fixTop(emotionRef.value);
    emits("setEmoBox", {
      x: left + width / 2,
      y: top,
    });
  }
}
function showRecordBox() {
  // this.showRecord = true;
}
function showHistoryBox() {
  // this.showHistory = true;
}
function onSwitchReceipt() {
  // this.isReceipt = !this.isReceipt;
  // this.refreshPlaceHolder();
}
function showPrivateVideo(mode: any) {
  // 检查是否被封禁
  if (props.isBanned) {
    emits("showBannedTip");
    return;
  }
  let rtcInfo = {
    mode: mode,
    isHost: true,
    friend: props.friend,
  };
  // 通过home.vue打开单人视频窗口
  // this.$eventBus.$emit("openPrivateVideo", rtcInfo);
}
function closeRefBox() {
  emoBoxRef.value?.close();
}
function onGroupVideo() {
  // 检查是否被封禁
  if (props.isBanned) {
    emits("showBannedTip");
    return;
  }
  // 邀请成员发起通话
  let ids = [props.mine.id];
  // let maxChannel = this.configStore.webrtc.maxChannel;
  // rtcSelRef.value.open(maxChannel, ids, ids, []);
}
function onInviteOk(members: any) {
  if (members.length < 2) {
    return;
  }
  let userInfos = [] as any;
  members.forEach((m: any) => {
    userInfos.push({
      id: m.userId,
      nickName: m.showNickName,
      headImage: m.headImage,
      isCamera: false,
      isMicroPhone: true,
    });
  });
  let rtcInfo = {
    isHost: true,
    groupId: props.group.id,
    inviterId: props.mine.id,
    userInfos: userInfos,
  };
  // 通过home.vue打开多人视频窗口
  // this.$eventBus.$emit("openGroupVideo", rtcInfo);
}
function generateId() {
  // 生成临时id
  return (
    String(new Date().getTime()) + String(Math.floor(Math.random() * 1000))
  );
}
function fillTargetId(msgInfo: any, targetId: string | number) {
  if (props.chat.type == "GROUP") {
    msgInfo.groupId = targetId;
  } else {
    msgInfo.recvId = targetId;
  }
}
function onImageBefore(file: any) {
  // 被封禁提示
  if (props.isBanned) {
    emits("showBannedTip");
    return;
  }
  let url = URL.createObjectURL(file);
  let data = {
    originUrl: url,
    thumbUrl: url,
  };
  let msgInfo = {
    id: 0,
    tmpId: generateId(),
    fileId: file.uid,
    sendId: props.mine.id,
    content: JSON.stringify(data),
    sendTime: new Date().getTime(),
    selfSend: true,
    type: 1,
    readedCount: 0,
    loadStatus: "loading",
    status: MESSAGE_STATUS.UNSEND,
  };
  // 填充对方id
  fillTargetId(msgInfo, props.chat.targetId);
  // 插入消息
  chatStore.insertMessage(msgInfo, props.chat);
  // 会话置顶
  emits("moveChatToTop");
  // // 滚动到底部
  emits("scrollToBottom");
  // 借助file对象保存
  file.msgInfo = msgInfo;
  file.chat = props.chat;
}
function onImageSuccess(data: any, file: any) {
  let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
  msgInfo.content = JSON.stringify(data);
  msgInfo.receipt = props.isReceipt;
  // this.sendMessageRequest(msgInfo).then((m) => {
  //   msgInfo.loadStatus = "ok";
  //   msgInfo.id = m.id;
  //
  //  chatStore.insertMessage(msgInfo, file.chat);
  // });
  emits("sendMessageRequest", msgInfo);
}
function onImageFail(e: any, file: any) {
  let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
  msgInfo.loadStatus = "fail";
  chatStore.insertMessage(msgInfo, file.chat);
}

function onFileSuccess(url: string, file: any) {
  let data = {
    name: file.name,
    size: file.size,
    url: url,
  };
  let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
  msgInfo.content = JSON.stringify(data);
  msgInfo.receipt = props.isReceipt;
  // this.sendMessageRequest(msgInfo).then((m) => {
  //   msgInfo.loadStatus = "ok";
  //   msgInfo.id = m.id;
  //   this.isReceipt = false;
  //   this.refreshPlaceHolder();
  //   this.chatStore.insertMessage(msgInfo, file.chat);
  // });
  emits("sendMessageRequest", msgInfo);
}
function onFileFail(e: any, file: any) {
  let msgInfo = JSON.parse(JSON.stringify(file.msgInfo));
  msgInfo.loadStatus = "fail";
  chatStore.insertMessage(msgInfo, file.chat);
}
function onFileBefore(file: any) {
  // 被封禁提示
  if (props.isBanned) {
    emits("showBannedTip");
    return;
  }
  let url = URL.createObjectURL(file);
  let data = {
    name: file.name,
    size: file.size,
    url: url,
  };
  let msgInfo = {
    id: 0,
    tmpId: generateId(),
    sendId: props.mine.id,
    content: JSON.stringify(data),
    sendTime: new Date().getTime(),
    selfSend: true,
    type: 2,
    loadStatus: "loading",
    readedCount: 0,
    status: MESSAGE_STATUS.UNSEND,
  };
  // 填充对方id
  fillTargetId(msgInfo, props.chat.targetId);
  // 插入消息
  chatStore.insertMessage(msgInfo, props.chat);
  // 会话置顶
  emits("moveChatToTop");
  // // 滚动到底部
  emits("scrollToBottom");
  // 借助file对象透传
  file.msgInfo = msgInfo;
  file.chat = props.chat;
}
defineExpose({
  closeRefBox,
});
</script>

<style lang="scss" scoped>
.chat-tool-bar {
  display: flex;
  position: relative;
  width: 100%;
  height: 36px;
  text-align: left;
  box-sizing: border-box;
  border-top: var(--im-border);
  padding: 4px 2px 2px 8px;

  > div {
    font-size: 22px;
    cursor: pointer;
    line-height: 30px;
    width: 30px;
    height: 30px;
    text-align: center;
    border-radius: 2px;
    margin-right: 8px;
    color: #999;
    transition: 0.3s;

    &.chat-tool-active {
      font-weight: 600;
      color: var(--im-color-primary);
      background-color: #ddd;
    }
  }

  > div:hover {
    color: #333;
  }
}
</style>
